<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="70px">
            <el-form-item label="订单号" prop="orderNumber">
                <el-input v-model="queryParams.orderNumber" placeholder="请输入订单号" clearable
                    @keyup.enter.native="handleQuery" style="width: 140px;" />
            </el-form-item>
            <el-form-item label="行程单号" prop="scheduleNumber">
                <el-input v-model="queryParams['travelSchedule.scheduleNumber']" placeholder="请输入行程单号" clearable
                    @keyup.enter.native="handleQuery" style="width: 140px;" />
            </el-form-item>
            <el-form-item label="客户姓名" prop="clientName">
                <el-input v-model="queryParams['travelClient.clientName']" placeholder="请输入姓名" clearable
                    @keyup.enter.native="handleQuery" style="width: 110px;" />
            </el-form-item>
            <el-form-item label="客户电话" prop="clientTel">
                <el-input v-model="queryParams['travelClient.clientTel']" placeholder="请输入电话号码" clearable
                    @keyup.enter.native="handleQuery" style="width: 140px;" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="orderList">
            <!-- 其他表格列 -->
<!--            <el-table-column label="序号" align="center" prop="orderId" :width="60" />-->
          <el-table-column label="序号" align="center" :width="60">
            <template slot-scope="scope">
              <!-- 公式：(当前页-1) * 每页条数 + 当前行索引 + 1 -->
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
            <el-table-column label="订单号" align="center" prop="orderNumber" :width="140" />
            <!-- 行程单号列 -->
            <el-table-column label="行程单号" align="center" prop="travelSchedule.scheduleNumber">
                <template slot-scope="scope">
                    <!-- 点击行程单号触发打开详情 -->
                    <span @click="openScheduleDetail(scope.row.travelSchedule.scheduleId)"
                        style="color: #409EFF; cursor: pointer; text-decoration: underline;">
                        {{ scope.row.travelSchedule.scheduleNumber }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="客户姓名" align="center" prop="travelSchedule.travelConsult.travelClient.clientName"  :width="90"/>
            <el-table-column label="地陪" align="center" prop="guideName" :width="90"/>
            <el-table-column label="定制师" align="center" prop="designerName" :width="90"/>
            <el-table-column label="订单金额" align="center" prop="travelSchedule.moneyTotal" :width="100" />
            <el-table-column label="客户电话" align="center" prop="travelSchedule.travelConsult.travelClient.clientTel"  :width="130"/>
            <el-table-column label="状态" align="center" :width="80">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === '0'">未开始</span>
                    <span v-if="scope.row.status === '1'">进行中</span>
                    <span v-if="scope.row.status === '2'">已结束</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleStart(scope.row)"
                        v-if="showStartButton(scope.row)">
                        开始
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleFollow(scope.row)"
                        v-if="showFollowButton(scope.row)">
                        跟进
                    </el-button>

                    <el-button size="mini" type="text" icon="el-icon-switch-button" @click="handleEnd(scope.row)"
                        v-if="showEndButton(scope.row)">
                        结束
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > '0'" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <ScheduleDetailDialog :visible.sync="scheduleDialogVisible" :schedule-id="currentScheduleId || ''"
            :is-detail-mode="true" />
    </div>
</template>

<script>
import { listOrder, updateOrder } from "@/api/travel/order";
import { listUser, getUser, getUserProfile } from '@/api/system/user'
import ScheduleDetailDialog from '@/components/Travel/ScheduleDetailDialog.vue';
export default {
    name: "Order",
    components: {
        ScheduleDetailDialog  // 注册组件
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            currentUserId: null,
            currentUserRoleName: '',
            scheduleDialogVisible: false,
            currentScheduleId: null,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 订单管理表格数据
            orderList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderNumber: null,
                status: null,
                scheduleNumber: null,
                moneyTotal: null,
                clientName: null,
                clientTel: null,
                'travelSchedule.scheduleNumber': null,
                'travelClient.clientName': null,
                'travelClient.clientTel': null,
                'travelSchedule.travelConsult.designerId': null,
                clientId: null,
                userId: this.currentUserId,
                userRoleName: this.currentUserRoleName,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {}
        };
    },
    created() {
        // 获取路由中的clientId
        this.clientId = this.$route.query.clientId || null;
        // 将clientId绑定到查询参数
        this.queryParams.clientId = this.clientId;
        this.getUserInfo()
    },
    watch: {
        // 监听路由参数变化
        '$route.query.clientId'(newClientId) {
            this.clientId = newClientId || null;
            this.queryParams.clientId = this.clientId; // 同步到查询参数
            this.getList(); // 重新加载列表
        }
    },
    methods: {
        // 哪种角色可以看到开始按钮
        showStartButton(row) {
            const role = this.currentUserRoleName
            const status = row.status
            if (role === '超级管理员') {
                return status === '0'
            }
            if (role === '地陪') {
                return status === '0'
            }
            return false
        },
        // 哪种角色可以看到跟进按钮
        showFollowButton(row) {
            const role = this.currentUserRoleName
            const status = row.status
            if (role === '超级管理员') return true
            if (role === '地陪') return true
            return false
        },

        // 哪种角色可以看到结束按钮
        showEndButton(row) {
            const role = this.currentUserRoleName
            const status = row.status
            if (role === '超级管理员') {
                return status === '1'
            }
            if (role === '地陪') {
                return status === '1'
            }
            return false
        },
        //获取用户信息
        getUserInfo() {
            try {
                getUserProfile().then(userProfileRes => {
                    // 1.保存当前用户的 userId
                    this.currentUserId = userProfileRes.data.userId
                    this.currentUserRoleName = userProfileRes.data.roles[0].roleName
                    // 2. 给 queryParams 赋值
                    this.queryParams.userId = this.currentUserId
                    this.queryParams.userRoleName = this.currentUserRoleName
                    // 3. 调用 getList 加载数据
                    this.getList()
                })
            } catch (error) {
                console.error('获取当前用户信息失败：', error)
                this.$message.error('获取用户信息失败，请刷新页面重试')
            }
        },
        async getUser(userId) {
            return await getUser(userId);
        },
        /** 新增：打开行程详情对话框 */
        openScheduleDetail(scheduleId) {
            if (!scheduleId) {
                this.$message.warning("未找到对应的行程ID");
                return;
            }
            // 设置ID
            this.currentScheduleId = scheduleId;
            // 显示对话框
            this.$nextTick(() => {
                this.scheduleDialogVisible = true;
            });
        },
        /** 查询订单管理列表 */
        async getList() {
          this.loading = true;
          try {
            const response = await listOrder(this.queryParams);
            this.orderList = response.rows || [];
            this.total = response.total || 0;
          } catch (error) {
            console.error("获取订单列表失败:", error);
            this.$message.error("获取订单列表失败，请重试");
          } finally {
            this.loading = false;
          }
        },
        // 表单重置
        reset() {
            this.form = {
                orderId: null,
                orderNumber: null,
                status: null,
                scheduleNumber: null,
                createBy: null,
                updateBy: null,
                createTime: null,
                updateTime: null,
                remark: null,
                moneyTotal: null,
                clientTel: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams['travelSchedule.scheduleNumber'] = null;
            this.queryParams['travelSchedule.travelConsult.designerId'] = null;
            this.queryParams['travelClient.clientName'] = null;
            this.queryParams['travelClient.clientTel'] = null;
            this.resetForm("queryForm");
            // 清除clientId参数
            this.queryParams.clientId = null;
            this.clientId = null;
            // 如果是从其他页面带clientId跳转过来的，清除路由参数
            if (this.$route.query.clientId) {
                this.$router.replace({
                    path: this.$route.path, // 保留当前路径
                    query: {} // 清除所有查询参数
                });
            }
            this.handleQuery();
        },

         //开始按钮
        async handleStart(row) {
            // 1. 确认用户操作
            await this.$confirm('确定要开始此订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            });
            // 2. 更新订单状态
            const response = await updateOrder({
                orderId: row.orderId,
                status: '1'
            });
            // 3. 提示成功并刷新列表
            this.$message.success('订单已开始');
            this.getList();  // 刷新列表
        },
         //跳转按钮
        handleFollow(row) {
            // 跳转到跟进页面
            this.$router.push({
                path: '/travel/follow',
                query: {
                    orderId: row.orderId // 传递订单ID
                }
            });
        },
        //结束按钮
        async handleEnd(row) {
            // 1. 确认
            await this.$confirm('确定要结束此订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            });
            // 2. 更新
            const response = await updateOrder({
                orderId: row.orderId,
                status: '2'
            });
            // 3. 成功并刷新列表
            this.$message.success('订单已结束');
            this.getList();
        }
    }
};
</script>
